package gr.takeda.rhythmguitar.data;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

public class XmlDataHandler {

	protected static final Logger logger = Logger.getLogger(XmlDataHandler.class);

	public static <T> T loadObject(File f, Class<T> classtype) throws JAXBException, FileNotFoundException, UnsupportedEncodingException {
		JAXBContext context = JAXBContext.newInstance(classtype);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		//return classtype.cast(unmarshaller.unmarshal(new FileReader(f)));
		return classtype.cast(unmarshaller.unmarshal(new InputStreamReader(new FileInputStream(f), "UTF8")));

	}

	public static <T> void saveObject(File file, Object obj, Class<T> classtype) throws IOException, JAXBException {
		JAXBContext context = JAXBContext.newInstance(classtype);
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		marshaller.marshal(obj, new FileWriter(file));
		marshaller.marshal(obj, new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
	}

	public static <T> T loadObject(String msg, Class<T> classtype) throws JAXBException {
		return classtype.cast(JAXBContext.newInstance(classtype).createUnmarshaller().unmarshal(new ByteArrayInputStream(msg.getBytes(Charset.forName("UTF-8")))));
	}

	public static <T> String saveObject(Object obj, Class<T> classtype) throws JAXBException {
		Marshaller marshaller = JAXBContext.newInstance(classtype).createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		StringWriter sw = new StringWriter(512);
		marshaller.marshal(obj, sw);
		return sw.toString();
	}
}
